package nz.ac.massey.cs.misc.timeoutthread;

import java.util.concurrent.*;

import nz.ac.massey.cs.misc.threats.RecursionWithoutTermination;

public class SurvivingAStackOverflow {
	
	static class RecursiveFunction implements Callable<Boolean> {
			@Override
			public Boolean call() throws Exception {
					new RecursionWithoutTermination().run();
					return true;
			}
		};

	public static void main(String[] args) throws Exception {
		
		System.out.println("Main thread is " + Thread.currentThread().getName());
		
		Thread.sleep(10000); // some time to start VisualVM
		
		ExecutorService executor = Executors.newFixedThreadPool(1);

		
		Future<Boolean> future = executor.submit(new RecursiveFunction());
		Thread.sleep(10000);
		
		// note that we can access the stack overflow error
		try {
			future.get();
		}
		catch (ExecutionException x) {
			System.out.println("execution failed with " + x.getCause());
		}
		
		System.out.println("I had enough - shooting down evil thread");
		future.cancel(true);
		
		Thread.sleep(5000);
		
		// not that the thread can be reused - lets do this again
		future = executor.submit(new RecursiveFunction());
		Thread.sleep(10000);
		future.cancel(true);
		
		System.out.println("shooting down another evil thread");
		System.exit(0);
	}

}
